package com.tyqx.hashchainutil.common;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tyqx.hashchainutil.org.app.config.Config;

import java.io.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class BlockData {

    public Map<String, String> getBlockByNum(Long blockNum, String channelName) {
        String COMPOSE_PROJECT_NAME = "hashchain";
        Map<String, String> blockMap = new HashMap<>();
        String blockDataStr = JsonFileReader.ReadFile("blockStr.json");
        blockMap.put("blockNum", String.valueOf(blockNum));
        blockMap.put("blockDataStr", blockDataStr);
        return blockMap;
    }


    public JsonObject getHashItemByTxId(JsonObject block, String txId) throws Exception {
        JsonArray dataArray = block.getAsJsonObject("data").getAsJsonArray("data");
        int txNum = dataArray.size();
        String hashItemStr = new String();
        for (int i = 0; i < txNum; i++) {
            JsonObject payloadJson = dataArray.get(i).getAsJsonObject().getAsJsonObject("payload");
            String blockTxIdStr = payloadJson.getAsJsonObject("header").getAsJsonObject("channel_header").get("tx_id").toString();
            String blockTxId = blockTxIdStr.substring(blockTxIdStr.indexOf("\"") + 1, blockTxIdStr.lastIndexOf("\""));
            JsonObject transactionJson = payloadJson.getAsJsonObject("data").getAsJsonArray("actions").get(0).getAsJsonObject();
            String hashItemBase64 = transactionJson.getAsJsonObject("payload").getAsJsonObject("action").getAsJsonObject("proposal_response_payload").getAsJsonObject("extension").getAsJsonObject("response").get("payload").toString();
            String hashItemBase64Str = hashItemBase64.substring(hashItemBase64.indexOf("\"") + 1, hashItemBase64.lastIndexOf("\""));
            hashItemStr = new String(Base64.getDecoder().decode(hashItemBase64Str), "UTF-8");
        }
        JsonObject jsonObject = new JsonParser().parse(hashItemStr).getAsJsonObject();
        return jsonObject;
    }
}
